package com.mxl.service.cashorder.rule;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.mxl.common.helper.ResponseErrorCode;
import com.mxl.common.rule.AbstractRule;
import com.mxl.dao.cashorder.impl.PurchaseOrderDaoImpl;
import com.mxl.service.cashorder.GatewayProcessService;
import com.mxl.service.cashorder.dto.CashOrderRequest;
import com.mxl.service.exception.AppServiceException;

public class GatewayProcessCheck extends AbstractRule {
	private static final Logger logger = LoggerFactory
			.getLogger(GatewayProcessCheck.class);

	@Resource(name = "gatewayProcessService")
	private GatewayProcessService gatewayProcessService;

	private static final String UPDATE_PURCHASE_ORDER = "update purchaseorder s set s.state=0 where s.cardpwd=?";

	@Resource(name = "purchaseOrderDao")
	private PurchaseOrderDaoImpl purchaseOrderDao;

	@Override
	protected boolean makeDecision(Object obj) throws Exception {
		// 根据密钥解密
		CashOrderRequest c = (CashOrderRequest) obj;
		try {
			gatewayProcessService.process(c);
		} catch (AppServiceException e) {
			c.setMsgId(e.getMessage());
			// logger.error("GatewayProcessCheck fail........", e);
			return false;
		} catch (Exception e) {
			c.setMsgId(ResponseErrorCode.SOKECT_EXCEPTION.getValue());
			logger.error("GatewayProcessCheck fail........", e);
			updatePurchaerorder(c);
			return false;
		}
		return true;
	}

	private void updatePurchaerorder(CashOrderRequest c) {
		try {
			purchaseOrderDao
			.executeSqlUpdate(UPDATE_PURCHASE_ORDER, c.getCardPwd());
		} catch (Exception e) {
			logger.error("GatewayProcessCheck update purchaseorder fail........", e);
		}
	}
}
